package il.ac.technion;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ModelAttribute;

@Controller
@RequestMapping(value = "/guest/*")
public class GuestController {
	@Autowired
	private TableDao tableDao;
	@Autowired
	private GuestDao guestDao;

	@RequestMapping(value = "add", method = RequestMethod.GET, params = {
			"name", "age", "tid" })
	public String add(Model m, Guest g, int tid) {
		m.addAttribute("cmd", "add");

		if (g.getAge() <= 0)
			return updateError(m, "Age of guest must be positive");

		Table t = tableDao.getObjectById(tid);
		if (t == null)
			return updateError(m, "Table " + tid + " does not exist");

		if (t.isFull())
			return updateError(m, "‫‪Table " + tid + " is full‬‬");

		t.addGuest(g);
		guestDao.saveObject(g);

		return "update_success";
	}

	@RequestMapping(value = "dislike", method = RequestMethod.GET, params = {
			"gid1", "gid2" })
	public String dislike(Model m, int gid1, int gid2) {
		m.addAttribute("cmd", "dislike");

		if (gid1 == gid2)
			return updateError(m, "Guest cannot dislike himself");

		Guest g1 = guestDao.getObjectById(gid1);
		if (g1 == null)
			return updateError(m, "Guest " + gid1 + " does not exist");

		Guest g2 = guestDao.getObjectById(gid2);
		if (g2 == null)
			return updateError(m, "Guest " + gid2 + " does not exist");

		g1.addDislike(g2);

		return "update_success";
	}

	@SuppressWarnings("unused")
	@ModelAttribute("type")
	private String getControllerType() {
		return "guest";
	}

	private String updateError(Model m, String errorMsg) {
		m.addAttribute("errorMsg", errorMsg);
		return "update_error";
	}
}
